// pages/exhibition/exhibit_detail.js
Page({
  data: {
    exhibitId: null,
    exhibitData: null,
    currentImageIndex: 0,
    videoSrc: '',
    audioSrc: '',
    isVideoPlaying: false,
    isAudioPlaying: false,
    imageList: [],
    videoList: [],
    currentVideoIndex: 0,
    showImagePreview: false,
    // 自定义音频UI所需状态
    audioCurrentTime: 0,
    audioDuration: 0,
    formattedCurrentTime: '00:00',
    formattedDuration: '00:00',
    audioSeeking: false,
    seekPreviewTime: 0,
    // 目录相关
    showCatalogModal: false,
    chapterList: [],
    exhibit_three: [],
    expandedChapters: {}
  },

  onLoad(options) {
    const exhibitId = (options && options.id) || null;
    if (exhibitId) {
      // 加载目录数据（与 map_guide2 同源接口）
      this.fetchChapterList();
      this.loadExhibitDetail(exhibitId);
    } else {
      wx.showToast({ title: '展项ID缺失', icon: 'none' });
      setTimeout(() => wx.navigateBack(), 1500);
    }
  },

  // 加载篇章+展项列表（供目录使用）
  fetchChapterList() {
    const apiUrl = 'https://nzy-api.congqian.cn/Api/admin/exhibit_one/get_exhibit_list';
    wx.request({
      url: apiUrl,
      method: 'GET',
      success: (res) => {
        if (res.data && res.data.code === 200 && res.data.data) {
          const payload = res.data.data;
          const list = (payload && (payload.one || payload)) || [];
          // 统一 children 字段
          const chapterList = list.map(ch => ({
            id: ch.id,
            name: ch.name,
            children: (ch.children || ch.list || []).map(it => ({ id: it.id, name: it.name, content: it.content, resource: it.resource || it.resources || it.item }))
          }));
          this.setData({ chapterList });
        }
      }
    });
  },

  // 加载展项详情
  loadExhibitDetail(exhibitId) {
    wx.showLoading({ title: '加载中...' });
    const apiUrl = 'https://nzy-api.congqian.cn/Api/admin/exhibit_three/mini_list';
    wx.request({
      url: apiUrl,
      method: 'GET',
      data: {id: exhibitId},
      success: (res) => {
        if (res.data && res.data.code === 200 && res.data.data) {
          const payload = res.data.data;
          const chapters = (payload && (payload.one || payload)) || [];
          let targetExhibit = null;
          for (let i = 0; i < chapters.length; i++) {
            if (chapters[i].current) {
              targetExhibit = chapters[i];
              this.setData({ exhibitId: chapters[i].id});
            }
          }
          if (targetExhibit) {
            this.setData({ exhibitData: targetExhibit, formattedCurrentTime: '00:00', audioCurrentTime: 0 ,exhibit_three: chapters});
            // 设置导航栏标题为展项名
            this.processExhibitResources(targetExhibit);
          } else {
            wx.showToast({ title: '展项不存在', icon: 'none' });
            setTimeout(() => wx.navigateBack(), 1500);
          }
        } else {
          wx.showToast({ title: '加载失败', icon: 'none' });
        }
      },
      fail: () => { wx.showToast({ title: '网络请求失败', icon: 'none' }); },
      complete: () => { wx.hideLoading(); }
    });
  },

  // 处理展项资源（图片、视频、音频）
  processExhibitResources(exhibit) {
    const imageList = exhibit.img || [];
    const videoList = exhibit.video || [];
    let audioSrc = exhibit.audio || '';

    // 如果没有从resources找到音频，尝试从其他字段提取
    if (!audioSrc) {
      audioSrc = this.extractAudioUrl(exhibit);
    }

    // 对富文本内容做移动端适配清洗（图片/视频宽度100%）
    const sanitizedContent = this.sanitizeHtmlContent(exhibit && exhibit.content ? String(exhibit.content) : '');
    const exhibitData = Object.assign({}, exhibit, { content: sanitizedContent });

    // 切换展项时重置音频状态与进度，并销毁旧的 innerAudio，确保 src 更新
    if (this.innerAudio) {
      try { this.innerAudio.stop(); this.innerAudio.destroy(); } catch(e) {}
      this.innerAudio = null;
    }

    this.setData({
      exhibitData,
      imageList,
      videoList,
      audioSrc,
      videoSrc: videoList.length > 0 ? videoList[0] : '',
      isAudioPlaying: false,
      audioCurrentTime: 0,
      formattedCurrentTime: '00:00',
      audioDuration: 0,
      formattedDuration: '00:00'
    });
  },

  // 提取音频URL（复用map_guide2逻辑）
  extractAudioUrl(item) {
    if (!item) return '';
    try {
      const content = item.content || item.description || item.desc || '';
      const m1 = /mp3:\s*([^,\s]+)/i.exec(content);
      if (m1 && m1[1]) return this.normalizeUrl(m1[1]);
      const m2 = /(https?:\/\/[^\s'\"]+\.(mp3|m4a|aac|wav))/i.exec(content);
      if (m2 && m2[1]) return this.normalizeUrl(m2[1]);
    } catch(e) {}
    return '';
  },

  // 规范化URL
  normalizeUrl(url) {
    if (!url) return '';
    if (url.startsWith('http')) return url;
    const baseOrigin = this.getBaseOrigin();
    return url.startsWith('/') ? baseOrigin + url : baseOrigin + '/' + url;
  },

  getBaseOrigin() {
    return 'https://nzy-api.congqian.cn';
  },

  // 图片预览
  previewImage(e) {
    const index = e.currentTarget.dataset.index;
    wx.previewImage({
      current: this.data.imageList[index],
      urls: this.data.imageList
    });
  },

  // 切换视频
  switchVideo(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      currentVideoIndex: index,
      videoSrc: this.data.videoList[index],
      isVideoPlaying: false
    });
  },

  // 视频播放控制
  onVideoPlay() { this.setData({ isVideoPlaying: true }); },
  onVideoPause() { this.setData({ isVideoPlaying: false }); },
  onVideoEnded() { this.setData({ isVideoPlaying: false }); },

  // 音频播放控制（自定义UI）
  toggleAudio() {
    if (!this.data.audioSrc) {
      wx.showToast({ title: '暂无音频资源', icon: 'none' });
      return;
    }

    if (!this.innerAudio) {
      this.createInnerAudio();
      this.innerAudio.src = this.data.audioSrc;
    }

    if (this.data.isAudioPlaying) {
      this.pauseAudio();
    } else {
      this.playAudio();
    }
  },

  createInnerAudio() {
    this.innerAudio = wx.createInnerAudioContext();
    this.innerAudio.obeyMuteSwitch = true;
    this.innerAudio.onPlay(() => { this.setData({ isAudioPlaying: true }); });
    this.innerAudio.onPause(() => { this.setData({ isAudioPlaying: false }); });
    this.innerAudio.onStop(() => { this.setData({ isAudioPlaying: false }); });
    this.innerAudio.onEnded(() => {
      this.setData({ isAudioPlaying: false, audioCurrentTime: this.data.audioDuration, formattedCurrentTime: this.formatTime(this.data.audioDuration) });
    });
    this.innerAudio.onError((err) => {
      console.error('音频播放错误:', err);
      this.setData({ isAudioPlaying: false });
      wx.showToast({ title: '音频播放失败', icon: 'none' });
    });
    // 时长就绪：多数机型需要延迟才能获取；若仍为0，进行有限次数重试
    const updateDuration = (retry=0) => {
      const d = Number(this.innerAudio.duration || 0);
      if (!isNaN(d) && d > 0) {
        this.setData({ audioDuration: d, formattedDuration: this.formatTime(d) });
      } else if (retry < 5) {
        setTimeout(() => updateDuration(retry + 1), 200);
      }
    };
    this.innerAudio.onCanplay(() => {
      setTimeout(() => updateDuration(0), 200);
    });
    // 进度更新
    this.innerAudio.onTimeUpdate(() => {
      if (this.data.audioSeeking) return; // 拖动时不被动刷新
      const cur = Number(this.innerAudio.currentTime || 0);
      const dur = Number(this.innerAudio.duration || this.data.audioDuration || 0);
      this.setData({
        audioCurrentTime: cur,
        formattedCurrentTime: this.formatTime(cur),
        audioDuration: dur > 0 ? dur : this.data.audioDuration,
        formattedDuration: this.formatTime(dur > 0 ? dur : this.data.audioDuration)
      });
    });
  },

  playAudio() {
    if (!this.innerAudio) {
      this.createInnerAudio();
    }
    // 若当前 audioSrc 与 innerAudio.src 不一致，则更新为最新音频并重置播放点
    if (this.innerAudio.src !== this.data.audioSrc) {
      try { this.innerAudio.stop(); } catch(e) {}
      this.innerAudio.src = this.data.audioSrc;
    }
    this.innerAudio.play();
  },

  pauseAudio() { if (this.innerAudio) { this.innerAudio.pause(); } },
  stopAudio() { if (this.innerAudio) { this.innerAudio.stop(); } },

  // 音频滑块拖动中（预览时间）
  onAudioSliderChanging(e) {
    const val = Number(e.detail.value || 0);
    this.setData({ audioSeeking: true, seekPreviewTime: val, formattedCurrentTime: this.formatTime(val) });
  },
  // 音频滑块松手，执行跳转
  onAudioSliderChange(e) {
    const val = Number(e.detail.value || 0);
    this.setData({ audioSeeking: false, audioCurrentTime: val, formattedCurrentTime: this.formatTime(val) });
    if (!this.innerAudio) {
      this.createInnerAudio();
      this.innerAudio.src = this.data.audioSrc;
    }
    try {
      this.innerAudio.seek(val);
      if (this.data.isAudioPlaying) { this.innerAudio.play(); }
    } catch (err) { console.error('seek 错误', err); }
  },

  formatTime(sec) {
    const s = Math.max(0, Math.floor(Number(sec) || 0));
    const mm = String(Math.floor(s / 60)).padStart(2, '0');
    const ss = String(s % 60).padStart(2, '0');
    return `${mm}:${ss}`;
  },

  onImageSwiperChange(e) {
    const current = (e && e.detail && typeof e.detail.current === 'number') ? e.detail.current : 0;
    this.setData({ currentImageIndex: current });
  },

  // 目录交互
  openCatalog() {
    // 默认展开所有或当前篇章：这里简单展开已有章节
    const expanded = { ...(this.data.expandedChapters || {}) };
    (this.data.chapterList || []).forEach(ch => { expanded[ch.id] = expanded[ch.id] || false; });
    this.setData({ showCatalogModal: true, expandedChapters: expanded });
  },
  closeCatalogModal() { this.setData({ showCatalogModal: false }); },
  toggleChapterExpand(e) {
    const id = e.currentTarget.dataset.id;
    const expanded = { ...(this.data.expandedChapters || {}) };
    expanded[id] = !expanded[id];
    this.setData({ expandedChapters: expanded });
  },
  // 二级展项目录点击事件
  selectCatalogExhibit(e) {
    const exhibitId = e.currentTarget.dataset.id;
    // 在 chapterList 中找到该展项并切换
    let target = null;
    let three_id = '';
    const three = this.data.exhibit_three || [];
    for (let i = 0; i < three.length; i++) {
      if (three[i].two_id == exhibitId) {
        target = three[i];
        three_id = three[i].id;
        // 展示该二级展项下的第一个展品，直接跳出
        break;
      }
    }
    if (target) {
      this.setData({ showCatalogModal: false, exhibitId: three_id });
      // 切换展示内容
      this.setData({ exhibitData: target });
      this.processExhibitResources(target);
    }
  },
  preventBubble() {},

  onUnload() {
    if (this.innerAudio) {
      try { this.innerAudio.destroy(); } catch(e) {}
      this.innerAudio = null;
    }
  },

  // 富文本HTML清洗，保证图片/视频自适应屏幕（作为 Page 方法）
  sanitizeHtmlContent(html) {
    if (!html || typeof html !== 'string') return html;
    let out = html;

    const ensureStyle = (attrs, extra) => {
      let a = attrs.replace(/\swidth=['\"][^'\"]*['\"]/gi, '')
                   .replace(/\sheight=['\"][^'\"]*['\"]/gi, '');
      if (/style=['\"]/i.test(a)) {
        a = a.replace(/style=['\"]([^'\"]*)['\"]/i, (m, s) => `style="${s};${extra}"`);
      } else {
        a = `${a} style="${extra}"`;
      }
      return a;
    };

    // img: 宽度100%、自适应高度、块级避免文字环绕
    out = out.replace(/<img\b([^>]*?)>/gi, (m, attrs) => {
      const a = ensureStyle(attrs, 'max-width:100%;height:auto;display:block');
      return `<img ${a}>`;
    });

    // video: 宽度100%、自适应高度
    out = out.replace(/<video\b([^>]*?)>/gi, (m, attrs) => {
      const a = ensureStyle(attrs, 'max-width:100%;height:auto;display:block');
      return `<video ${a}>`;
    });

    // table: 宽度100%、固定布局避免溢出
    out = out.replace(/<table\b([^>]*?)>/gi, (m, attrs) => {
      const a = ensureStyle(attrs, 'width:100%;table-layout:fixed');
      return `<table ${a}>`;
    });

    return out;
  },

  // 切换到上一个展项
  bindUpTap() {
    const currentExhibitId = this.data.exhibitId;
    
    // 找到当前展项的位置
    let currentIndex = -1;
    let allExhibits = this.data.exhibit_three;
    
    // 找到当前展项的索引
    currentIndex = allExhibits.findIndex(exhibit => String(exhibit.id) === String(currentExhibitId));
    
    if (currentIndex > 0) {
      // 有上一个展项
      const prevExhibit = allExhibits[currentIndex - 1];
      this.switchToExhibit(prevExhibit);
    } else {
      // 已经是第一个展项
      wx.showToast({
        title: '已经是第一个展项',
        icon: 'none',
        duration: 1500
      });
    }
  },

  // 切换到下一个展项
  bindDownTap() {
    const currentExhibitId = this.data.exhibitId;
    
    // 找到当前展项的位置
    let currentIndex = -1;
    let allExhibits = this.data.exhibit_three;
    
    // 找到当前展项的索引
    currentIndex = allExhibits.findIndex(exhibit => String(exhibit.id) === String(currentExhibitId));

    if (currentIndex >= 0 && currentIndex < allExhibits.length - 1) {
      // 有下一个展项
      const nextExhibit = allExhibits[currentIndex + 1];
      this.switchToExhibit(nextExhibit);
    } else {
      // 已经是最后一个展项
      wx.showToast({
        title: '已经是最后一个展项',
        icon: 'none',
        duration: 1500
      });
    }
  },

  // 切换到指定展项的通用方法
  switchToExhibit(exhibit) {
    if (!exhibit || !exhibit.id) return;
    
    const exhibitId = exhibit.id;
    
    // 更新页面状态
    this.setData({
      exhibitId,
      exhibitData: exhibit,
      showCatalogModal: false
    });
    
    // 处理展项资源
    this.processExhibitResources(exhibit);
    
    // 滚动到页面顶部
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    });
  },

});